import React, { useState, useEffect, useRef } from 'react';
import { Spin, Button, message, Input, Card, Avatar, Typography, Select } from 'antd';
import { EditOutlined, RobotOutlined, SendOutlined, UserOutlined, CloseOutlined } from '@ant-design/icons';
import 'highlight.js/styles/github-dark.min.css';
import '../assets/css/DocGroupView.css';
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { prism } from 'react-syntax-highlighter/dist/cjs/styles/prism';
import MarkdownNavbar from 'markdown-navbar';
import 'markdown-navbar/dist/navbar.css';
import MDEditor, { commands } from '@uiw/react-md-editor';
import { saveDocument, saveDocumentToCache } from '../api/document';
import { sendStreamingChatMessage, sendChatMessage, generateChatId, sendManusStreamingChatMessage } from '../api/ai';
import ResizablePanel from '../components/ResizablePanel';

// 类型定义
interface CodeProps {
    node?: any;
    inline?: boolean;
    className?: string;
    children?: React.ReactNode;
}

interface ImgProps {
    src?: string;
    alt?: string;
}

interface BlockquoteProps {
    children?: React.ReactNode;
}

interface TableProps {
    children?: React.ReactNode;
}

interface ThTdProps {
    children?: React.ReactNode;
}

interface ChatMessage {
    id: string;
    type: 'user' | 'ai';
    content: string;
    timestamp: Date;
}

interface Document {
    id: string;
    groupId: string;
    baseId: string;
    content: string;
    title?: string;
    sortOrder: number;
}

interface DocumentViewProps {
    activeDoc: Document | null;
    docContent: string;
    loadingDoc: boolean;
    onDocumentUpdated?: (updatedDoc: Document) => void;
    onImportDocument: () => void;
}

const DocumentView: React.FC<DocumentViewProps> = ({
    activeDoc,
    docContent,
    loadingDoc,
    onDocumentUpdated,
    onImportDocument
}) => {
    const [editing, setEditing] = useState(false);
    const [localContent, setLocalContent] = useState('');
    const [tocVisible, setTocVisible] = useState(true);
    const [aiChatVisible, setAiChatVisible] = useState(false);
    const [chatMessages, setChatMessages] = useState<ChatMessage[]>([]);
    const [inputMessage, setInputMessage] = useState('');
    const [isAiTyping, setIsAiTyping] = useState(false);
    const [chatId] = useState(() => generateChatId());
    const [streamingMessageId, setStreamingMessageId] = useState<string | null>(null);
    const [completeStreamedContent, setCompleteStreamedContent] = useState<string>('');
    const [selectedModel, setSelectedModel] = useState<string>('default');
    const containerRef = useRef<HTMLDivElement>(null);
    const scrollContainerRef = useRef<HTMLDivElement>(null);
    const chatContainerRef = useRef<HTMLDivElement>(null);
    const closeStreamRef = useRef<(() => void) | null>(null);
    const streamContentRef = useRef<string>('');

    useEffect(() => {
        setLocalContent(docContent);
    }, [docContent]);

    // Add keyboard event listener for Ctrl+S to save document to cache
    useEffect(() => {
        const handleKeyDown = (e: KeyboardEvent) => {
            if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                e.preventDefault(); // Prevent the browser's save dialog
                if (activeDoc) {
                    saveDocumentToCache({
                        id: activeDoc.id,
                        content: editing ? localContent : docContent
                    })
                        .then(() => {
                            message.success('文档已保存');
                        })
                        .catch(error => {
                            console.error("保存文档失败:", error);
                            message.error('保存到缓存失败');
                        });
                }
            }
        };

        document.addEventListener('keydown', handleKeyDown);
        return () => {
            document.removeEventListener('keydown', handleKeyDown);
        };
    }, [activeDoc, docContent, localContent, editing]);

    // Auto scroll chat to bottom when new messages arrive
    useEffect(() => {
        if (chatContainerRef.current) {
            chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
        }
    }, [chatMessages]);

    // Clean up streaming connection on unmount
    useEffect(() => {
        return () => {
            if (closeStreamRef.current) {
                closeStreamRef.current();
            }
        };
    }, []);

    const handleSaveEdit = () => {
        if (!activeDoc) return;
        
        const updatedDoc: Document = {
            ...activeDoc,
            content: localContent
        };
        
        saveDocument(updatedDoc)
            .then(() => {
                message.success('文档更新成功');
                setEditing(false);
                // 通知父组件文档已更新
                if (onDocumentUpdated) {
                    onDocumentUpdated(updatedDoc);
                }
            })
            .catch(error => {
                console.error("更新文档失败:", error);
                message.error('文档更新失败');
            });
    };

    const handleAiChat = () => {
        setAiChatVisible(true);
        setTocVisible(false);
    };

    const handleCloseChatAi = () => {
        setAiChatVisible(false);
        setTocVisible(true);
        // Close any active streaming connection
        if (closeStreamRef.current) {
            closeStreamRef.current();
            closeStreamRef.current = null;
        }
    };

    const handleSendMessage = () => {
        if (!inputMessage.trim() || isAiTyping) return;

        const userMessage: ChatMessage = {
            id: `user_${Date.now()}`,
            type: 'user',
            content: inputMessage.trim(),
            timestamp: new Date()
        };

        setChatMessages(prev => [...prev, userMessage]);
        setInputMessage('');
        setIsAiTyping(true);

        // Create AI message placeholder
        const aiMessageId = `ai_${Date.now()}`;
        const aiMessage: ChatMessage = {
            id: aiMessageId,
            type: 'ai',
            content: '',
            timestamp: new Date()
        };

        setChatMessages(prev => [...prev, aiMessage]);

        console.log('发送AI消息:', userMessage.content, 'chatId:', chatId);

        // Check if we should use real API or mock data
        const USE_REAL_API = true; // Set to true when backend API is ready

        const generateMockResponse = () => {
            const responses = [
                `Hello! I'm an AI assistant. You just said: "${userMessage.content}". I'm happy to help you!`,
                `Regarding "${userMessage.content}", let me provide you with a detailed answer...`,
                `I understand your question: "${userMessage.content}". Let me analyze this for you.`,
                `Thank you for your question: "${userMessage.content}". This is a great question!`,
                `For "${userMessage.content}", I suggest you can consider the following aspects...`
            ];
            
            const randomResponse = responses[Math.floor(Math.random() * responses.length)];
            
            // Simulate typing effect
            let currentText = '';
            const words = randomResponse.split('');
            let index = 0;
            
            const typeInterval = setInterval(() => {
                if (index < words.length) {
                    currentText += words[index];
                    setChatMessages(prev => 
                        prev.map(msg => 
                            msg.id === aiMessageId 
                                ? { ...msg, content: currentText }
                                : msg
                        )
                    );
                    index++;
                } else {
                    clearInterval(typeInterval);
                    setIsAiTyping(false);
                }
            }, 50); // Type one character every 50ms
            
            // Store the interval ID so we can clear it if needed
            closeStreamRef.current = () => {
                clearInterval(typeInterval);
                setIsAiTyping(false);
            };
        };

        if (USE_REAL_API) {
            // Try real API first, fallback to mock if it fails
            try {
                // Use the appropriate API endpoint based on the selected model
                if (selectedModel === 'manus') {
                    // Use Manus API
                    // Set streaming message ID to track the current message being updated
                    setStreamingMessageId(aiMessageId);
                    
                    // Reset the stream content
                    streamContentRef.current = '';
                    
                    closeStreamRef.current = sendManusStreamingChatMessage(
                        userMessage.content,
                        activeDoc?.id,
                        (chunk) => {
                            // Accumulate content in the ref
                            streamContentRef.current += chunk;
                            
                            setChatMessages(prev => 
                                prev.map(msg => 
                                    msg.id === aiMessageId 
                                        ? { ...msg, content: streamContentRef.current }
                                        : msg
                                )
                            );
                        },
                        (error) => {
                            console.error('Manus streaming error:', error);
                            setIsAiTyping(false);
                            setStreamingMessageId(null);
                            
                            // If we haven't received any content, fall back to mock
                            if (!streamContentRef.current.trim()) {
                                console.error('No content received from Manus API, using mock data');
                                generateMockResponse();
                            }
                        },
                        () => {
                            console.log('Manus response completed');
                            setIsAiTyping(false);
                            setStreamingMessageId(null);
                            closeStreamRef.current = null;
                        }
                    );
                } else {
                    // Use default API
                    closeStreamRef.current = sendStreamingChatMessage(
                        userMessage.content,
                        chatId,
                        activeDoc?.id,
                        (chunk) => {
                            console.log('Received AI response chunk:', chunk);
                            
                            // Accumulate content in the ref
                            streamContentRef.current += chunk;

                            setChatMessages(prev => 
                                prev.map(msg => 
                                    msg.id === aiMessageId 
                                        ? { ...msg, content: isAiTyping ? "正在生成回答..." : streamContentRef.current }
                                        : msg
                                )
                            );
                        },
                        async (error) => {
                            // Only try sync API if we haven't received any content yet
                            const currentMessages = [...chatMessages];
                            const aiMessage = currentMessages.find(msg => msg.id === aiMessageId);
                            
                            if (aiMessage && aiMessage.content.trim() !== '') {
                                // If we already have some content, consider it a successful completion
                                console.log('SSE connection closed but we received content, treating as complete');
                                setIsAiTyping(false);
                                return;
                            }
                            
                            console.error('Streaming AI response failed, trying sync API:', error);
                            
                            try {
                                const response = await sendChatMessage(userMessage.content, chatId);
                                setChatMessages(prev => 
                                    prev.map(msg => 
                                        msg.id === aiMessageId 
                                            ? { ...msg, content: response }
                                            : msg
                                    )
                                );
                                setIsAiTyping(false);
                            } catch (syncError) {
                                console.error('Sync AI response also failed, using mock data:', syncError);
                                // Fallback to mock response
                                generateMockResponse();
                            }
                        },
                        () => {
                            console.log('AI response completed');
                            setIsAiTyping(false);
                            closeStreamRef.current = null;
                        }
                    );
                }
            } catch (error) {
                console.error('API call failed, using mock data:', error);
                generateMockResponse();
            }
        } else {
            // Use mock response directly - no API calls
            console.log('Using mock AI response (backend APIs not available)');
            setTimeout(generateMockResponse, 500); // Simulate network delay
        }
    };

    const handleKeyPress = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSendMessage();
        }
    };

    // Markdown渲染组件
    const MarkdownRender = ({ content, isChat = false }: { content: string; isChat?: boolean }) => (
        <div ref={isChat ? undefined : containerRef} data-color-mode="light">
            <MDEditor.Markdown
                source={content}
                remarkPlugins={[remarkGfm]}
                rehypePlugins={[rehypeRaw]}
                components={{
                    code: ({ inline, className, children }: CodeProps) => {
                        const match = /language-(\w+)/.exec(className || '');
                        
                        // Extract text content from React elements
                        const extractTextContent = (node: any): string => {
                            if (typeof node === 'string') return node;
                            if (typeof node === 'number') return String(node);
                            if (Array.isArray(node)) return node.map(extractTextContent).join('');
                            if (node && typeof node === 'object' && node.props && node.props.children) {
                                return extractTextContent(node.props.children);
                            }
                            return '';
                        };
                        
                        const codeContent = extractTextContent(children);
                        
                        return !inline && match ? (
                            <div style={{ position: 'relative' }}>
                                <div style={{
                                    position: 'absolute',
                                    top: 8,
                                    right: 12,
                                    fontSize: 11,
                                    color: '#666',
                                    zIndex: 1,
                                    background: 'rgba(255,255,255,0.8)',
                                    padding: '2px 6px',
                                    borderRadius: 3
                                }}>
                                    {match[1]}
                                </div>
                                <SyntaxHighlighter
                                    style={prism}
                                    language={match[1].toLowerCase()}
                                    PreTag="div"
                                    showLineNumbers={!isChat}
                                    customStyle={{
                                        margin: isChat ? '8px 0' : '16px 0',
                                        borderRadius: 6,
                                        padding: isChat ? '12px !important' : '16px !important',
                                        fontSize: isChat ? 12 : 14,
                                        background: '#fff',
                                        border: '1px solid #d0d7de',
                                        color: '#24292f'
                                    }}
                                >
                                    {codeContent.replace(/\n$/, '')}
                                </SyntaxHighlighter>
                            </div>
                        ) : (
                            <code
                                className={className}
                                style={{
                                    background: '#f6f8fa',
                                    padding: '2px 6px',
                                    borderRadius: 4,
                                    color: '#d73a49',
                                    fontSize: '90%',
                                    border: '1px solid #d0d7de'
                                }}
                            >
                                {codeContent}
                            </code>
                        );
                    },
                    img: ({ src, alt }: ImgProps) => (
                        <div style={{ textAlign: 'center', margin: isChat ? '12px 0' : '24px 0' }}>
                            <img
                                src={src}
                                alt={alt}
                                style={{
                                    maxWidth: '100%',
                                    borderRadius: 8,
                                    boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
                                    display: 'inline-block'
                                }}
                            />
                            {alt && <div style={{
                                marginTop: isChat ? 8 : 12,
                                color: '#666',
                                fontSize: isChat ? 12 : 14,
                                fontStyle: 'italic'
                            }}>{alt}</div>}
                        </div>
                    ),
                    blockquote: ({ children }: BlockquoteProps) => (
                        <blockquote style={{
                            borderLeft: '4px solid #d0d7de',
                            padding: isChat ? '12px 16px' : '16px 20px',
                            margin: isChat ? '12px 0' : '24px 0',
                            backgroundColor: '#f6f8fa',
                            color: '#656d76',
                            borderRadius: '0 8px 8px 0',
                            fontSize: isChat ? '13px' : 'inherit'
                        }}>
                            {children}
                        </blockquote>
                    ),
                    table: ({ children }: TableProps) => (
                        <div style={{ overflowX: 'auto', margin: isChat ? '12px 0' : '24px 0' }}>
                            <table style={{
                                width: '100%',
                                borderCollapse: 'collapse',
                                boxShadow: '0 1px 3px rgba(0,0,0,0.1)',
                                fontSize: isChat ? '12px' : 'inherit'
                            }}>
                                {children}
                            </table>
                        </div>
                    ),
                    th: ({ children }: ThTdProps) => (
                        <th style={{
                            padding: '12px 16px',
                            textAlign: 'left',
                            backgroundColor: '#f6f8fa',
                            border: '1px solid #d0d7de',
                            fontWeight: 600
                        }}>
                            {children}
                        </th>
                    ),
                    td: ({ children }: ThTdProps) => (
                        <td style={{
                            padding: '12px 16px',
                            border: '1px solid #d0d7de',
                            backgroundColor: '#fff'
                        }}>
                            {children}
                        </td>
                    )
                }}
            />
        </div>
    );

    return (
        <div style={{
            width: '100%',
            display: 'flex',
            flexDirection: 'column',
            background: '#fff',
            height: '100%',
            overflow: 'hidden'
        }}>
            {/* 顶部操作栏 */}
            <div style={{
                padding: '12px 24px',
                borderBottom: '1px solid #eee',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                background: '#fafafa',
                flexShrink: 0
            }}>
                <div style={{ fontWeight: 'bold', fontSize: 16 }}>
                    {activeDoc ? (activeDoc.title || '未命名文档') : '请选择文档'}
                </div>

                <div>
                    {activeDoc ? (
                        <>
                            <Button
                                type={aiChatVisible ? 'primary' : 'default'}
                                icon={<RobotOutlined />}
                                onClick={handleAiChat}
                                disabled={loadingDoc}
                                style={{ marginRight: 8 }}
                            >
                                AI
                            </Button>

                            <Button
                                type={editing ? 'default' : 'primary'}
                                icon={<EditOutlined />}
                                onClick={() => {
                                    if (editing) {
                                        handleSaveEdit();
                                    } else {
                                        setEditing(true);
                                    }
                                }}
                                disabled={loadingDoc}
                                style={{ marginRight: 8 }}
                            >
                                {editing ? '更新' : '编辑'}
                            </Button>
                        </>
                    ) : null}

                    {!editing && docContent && !aiChatVisible && (
                        <Button
                            type={tocVisible ? 'primary' : 'default'}
                            onClick={() => setTocVisible(!tocVisible)}
                        >
                            {tocVisible ? '隐藏目录' : '显示目录'}
                        </Button>
                    )}

                    {aiChatVisible && (
                        <Button
                            type="default"
                            icon={<CloseOutlined />}
                            onClick={handleCloseChatAi}
                        >
                            关闭AI
                        </Button>
                    )}

                    {editing && (
                        <Button
                            style={{ marginLeft: 8 }}
                            onClick={() => setEditing(false)}
                        >
                            取消
                        </Button>
                    )}
                </div>
            </div>

            {/* 内容区域 */}
            <div style={{
                flex: 1,
                overflow: 'hidden',
                display: 'flex',
                flexDirection: 'row',
                background: '#fff',
                width: '100%',
                padding: 0,
                margin: 0
            }}>
                {loadingDoc ? (
                    <div style={{
                        display: 'flex',
                        justifyContent: 'center',
                        alignItems: 'center',
                        width: '100%',
                        height: '100%'
                    }}>
                        <Spin size="large" />
                    </div>
                ) : editing ? (
                    // 编辑模式占满整个区域，紧贴左右两侧
                    <div style={{
                        flex: 1,
                        display: 'flex',
                        alignItems: 'stretch',
                        justifyContent: 'stretch',
                        background: '#fff',
                        minHeight: 0,
                        width: '100%',
                        padding: 0,
                        margin: 0
                    }}>
                        <MDEditor
                            value={localContent}
                            onChange={(val) => setLocalContent(val || '')}
                            height="100%"
                            preview="live"
                            visibleDragbar={false}
                            style={{
                                width: '100%',
                                margin: 0,
                                padding: 0,
                                border: 'none',
                                borderRadius: 0
                            }}
                            textareaProps={{
                                placeholder: '输入Markdown内容...',
                                style: {
                                    padding: 0
                                }
                            }}
                            commands={[
                                commands.title1,
                                commands.title2,
                                commands.title3,
                                commands.divider,
                                commands.bold,
                                commands.italic,
                                commands.strikethrough,
                                commands.divider,
                                commands.unorderedListCommand,
                                commands.orderedListCommand,
                                commands.quote,
                                commands.divider,
                                commands.codeBlock,
                                commands.link,
                                commands.image,
                                commands.divider,
                                commands.table,
                                commands.hr,
                                commands.divider,
                                commands.fullscreen
                            ]}
                            previewOptions={{
                                className: 'custom-preview',
                                style: {
                                    padding: '16px',
                                    backgroundColor: '#fff',
                                    margin: 0
                                }
                            }}
                        />
                    </div>
                ) : docContent ? (
                    // 预览模式
                    <>
                        {aiChatVisible ? (
                            <ResizablePanel
                                left={
                                    <div
                                        ref={scrollContainerRef}
                                        style={{
                                            width: '100%',
                                            overflowY: 'auto',
                                            padding: '24px 48px',
                                            height: '100%',
                                            textAlign: 'left',
                                            background: '#fff'
                                        }}>
                                        <MarkdownRender content={docContent} isChat={false} />
                                    </div>
                                }
                                right={
                                    <div style={{
                                        width: '100%',
                                        background: '#fff',
                                        height: '100%',
                                        display: 'flex',
                                        flexDirection: 'column'
                                    }}>
                                        {/* 聊天标题 */}
                                        <div style={{
                                            padding: '16px',
                                            borderBottom: '1px solid #eee',
                                            fontSize: 16,
                                            fontWeight: 'bold',
                                            display: 'flex',
                                            alignItems: 'center',
                                            gap: 8
                                        }}>
                                            <RobotOutlined style={{ color: '#1890ff' }} />
                                            <span>AI助手</span>
                                        </div>

                                        {/* 聊天消息区域 */}
                                        <div 
                                            ref={chatContainerRef}
                                            style={{
                                                flex: 1,
                                                overflowY: 'auto',
                                                padding: '16px',
                                                display: 'flex',
                                                flexDirection: 'column',
                                                gap: 12
                                            }}
                                        >
                                            {chatMessages.length === 0 ? (
                                                <div style={{
                                                    textAlign: 'center',
                                                    color: '#999',
                                                    padding: '40px 20px'
                                                }}>
                                                    <RobotOutlined style={{ fontSize: 32, marginBottom: 16, color: '#ccc' }} />
                                                    <p>你好！我是AI助手，有什么可以帮助你的吗？</p>
                                                </div>
                                            ) : (
                                                chatMessages.map((msg) => (
                                                    <div key={msg.id} style={{
                                                        display: 'flex',
                                                        flexDirection: msg.type === 'user' ? 'row-reverse' : 'row',
                                                        gap: 8,
                                                        alignItems: 'flex-start'
                                                    }}>
                                                        <Avatar 
                                                            size="small" 
                                                            icon={msg.type === 'user' ? <UserOutlined /> : <RobotOutlined />}
                                                            style={{
                                                                backgroundColor: msg.type === 'user' ? '#1890ff' : '#52c41a',
                                                                flexShrink: 0
                                                            }}
                                                        />
                                                        <div style={{
                                                            maxWidth: '80%',
                                                            padding: '8px 12px',
                                                            borderRadius: 8,
                                                            backgroundColor: msg.type === 'user' ? '#1890ff' : '#f6f6f6',
                                                            color: msg.type === 'user' ? '#fff' : '#333',
                                                            wordBreak: 'break-word',
                                                            whiteSpace: msg.type === 'user' ? 'pre-wrap' : 'normal',
                                                            textAlign: 'left'
                                                        }}>
                                                            {msg.type === 'ai' ? (
                                                                msg.content ? (
                                                                    <div style={{ 
                                                                        color: '#333',
                                                                        fontSize: '14px',
                                                                        lineHeight: '1.6'
                                                                    }}>
                                                                        {isAiTyping && msg.id === streamingMessageId ? (
                                                                            <span style={{ opacity: 0.6 }}>正在生成回答...</span>
                                                                        ) : (
                                                                            <MarkdownRender content={msg.content} isChat={true} />
                                                                        )}
                                                                    </div>
                                                                ) : isAiTyping ? (
                                                                    <span style={{ opacity: 0.6 }}>正在思考...</span>
                                                                ) : null
                                                            ) : (
                                                                msg.content
                                                            )}
                                                        </div>
                                                    </div>
                                                ))
                                            )}
                                        </div>

                                        {/* 输入区域 */}
                                        <div style={{
                                            padding: '16px',
                                            borderTop: '1px solid #eee',
                                            backgroundColor: '#fafafa'
                                        }}>
                                            <Input.TextArea
                                                value={inputMessage}
                                                onChange={(e) => setInputMessage(e.target.value)}
                                                onKeyPress={handleKeyPress}
                                                placeholder="输入你的问题..."
                                                autoSize={{ minRows: 2, maxRows: 4 }}
                                                disabled={isAiTyping}
                                                style={{ marginBottom: 8 }}
                                            />
                                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                                <Select
                                                    value={selectedModel}
                                                    onChange={(value) => setSelectedModel(value)}
                                                    style={{ width: 150 }}
                                                    options={[
                                                        { value: 'default', label: '默认模型' },
                                                        { value: 'manus', label: 'Manus 超级智能体' }
                                                    ]}
                                                />
                                                <Button
                                                    type="primary"
                                                    icon={<SendOutlined />}
                                                    onClick={handleSendMessage}
                                                    disabled={!inputMessage.trim() || isAiTyping}
                                                    loading={isAiTyping}
                                                >
                                                    发送
                                                </Button>
                                            </div>
                                        </div>
                                    </div>
                                }
                                initialLeftWidth={window.innerWidth / 2}
                                minLeftWidth={window.innerWidth * 0.3}
                                maxLeftWidth={window.innerWidth * 0.7}
                            />
                        ) : (
                            <>
                                {/* 文章内容左对齐 */}
                                <div
                                    ref={scrollContainerRef}
                                    style={{
                                        flex: 1,
                                        overflowY: 'auto',
                                        padding: '24px 48px',
                                        height: '100%',
                                        textAlign: 'left',
                                        background: '#fff',
                                        borderRight: tocVisible ? '1px solid #eee' : 'none'
                                    }}>
                                    <MarkdownRender content={docContent} isChat={false} />
                                </div>

                                {/* 目录在右侧 */}
                                {tocVisible && (
                                    <div style={{
                                        width: 280,
                                        background: '#fff',
                                        borderLeft: '1px solid #eee',
                                        overflowY: 'auto',
                                        padding: 16,
                                        height: '100%',
                                        textAlign: 'left' // 目录左对齐
                                    }}>
                                        <div style={{
                                            fontSize: 16,
                                            fontWeight: 'bold',
                                            marginBottom: 16,
                                            display: 'flex',
                                            alignItems: 'center',
                                            textAlign: 'left'
                                        }}>
                                            <span>文档目录</span>
                                        </div>
                                        <MarkdownNavbar
                                            source={docContent}
                                            ordered={false}
                                            headingTopOffset={80}
                                            onNavItemClick={(e, element) => {
                                                e.preventDefault();
                                                if (element && scrollContainerRef.current) {
                                                    // Calculate the element's position relative to the scroll container
                                                    const containerRect = scrollContainerRef.current.getBoundingClientRect();
                                                    const elementRect = element.getBoundingClientRect();
                                                    const relativeTop = elementRect.top - containerRect.top + scrollContainerRef.current.scrollTop;
                                                    
                                                    scrollContainerRef.current.scrollTo({
                                                        top: relativeTop - 80, // Adjust for fixed headers and padding
                                                        behavior: 'smooth',
                                                    });
                                                }
                                            }}
                                            className="markdown-navbar-left-align"
                                        />
                                    </div>
                                )}
                            </>
                        )}
                    </>
                ) : (
                    // 空状态
                    <div style={{
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'center',
                        justifyContent: 'center',
                        width: '100%',
                        height: '100%',
                        color: '#999',
                        textAlign: 'center',
                        padding: '20px'
                    }}>
                        <div style={{ fontSize: 48, marginBottom: 24 }}>📄</div>
                        <h3 style={{ fontWeight: 'normal', marginBottom: 12, fontSize: 20 }}>没有选择文档</h3>
                        <p style={{ maxWidth: 500, lineHeight: 1.7, fontSize: 15, color: '#666' }}>
                            请从左侧列表中选择一个文档进行查看，或点击左侧分组中的"+"按钮添加新的文档
                        </p>
                    </div>
                )}
            </div>
        </div>
    );
};

export default DocumentView;
